package xx.services.entity.rest;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.sql.SQLException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.Context;

import xx.entity.bas.Attach;
import xx.entity.bas.Entity;
import xx.entity.bas.Picture;
import xx.entity.bas.Xfile;
import xx.entity.bas.dao.EntityDao;
import xx.services.Passport;
import xx.services.Upload;
import xx.services.entity.inter.IXfileInterface;
import xx.services.util.Constants;
import xx.services.util.Results;
import xx.util.property.Config;
import xx.util.string.Format;

/**
 * 文件管理服务接口
 * 
 * @author dengjinye,2010-12-18 $LastChangedDate$ $Author$
 */
@Path(Constants.RESTFUL_ROOT_PATH + "/file")
public class XfileRest extends Passport implements IXfileInterface
{
    public XfileRest(@Context
    HttpServletRequest request)
    {
        super(request);
        // TODO Auto-generated constructor stub
    }

    /**
     * 删除文件
     * 
     * @param fileId
     *            -@PathParam("file_id") 文件ID，多个文件ID用“_”分隔
     * @return 文件实体列表
     */
    @DELETE
    @Path("/{file_id}")
    public String deleteFile(@PathParam("file_id")
    String fileId)
    {
        // TODO Auto-generated method stub
        return null;
    }

    /**
     * 获取所有文件列表，最新上传的排在最前面<br>
     * 可根据文件类型（type）、文件大小（size）、上传时间（create_date）等筛选
     * 
     * @return 文件实体列表
     */
    @GET
    public String getFile()
    {
        try
        {
            Xfile file = new Xfile(qr, owner);

            return ok(file.getFiles(pageSize, pageNo, condition, orderField));
        }
        catch (Exception e)
        {
            return error(e);
        }
    }

    @GET
    @Path("/download/{file_id}")
    public String downFile(@Context
    HttpServletResponse response, @PathParam("file_id")
    String fileId)
    {
        try
        {
            Xfile file = new Xfile(qr, owner);
            file.setFileId(Format.strToLong(fileId)).load();
            String pageHtmlFolder = Config.getInstance().get(Constants.PAGE_HTML_FOLDER);
            String root = Format.isEmpty(pageHtmlFolder) ? xx.util.Path.getRootPath() : pageHtmlFolder;
            String path = root + file.getOrigin();
            String fileName = file.getName();
            response.reset();
            // response.setContentType("application/x-download;charset=utf-8");//iso-8859-1
            response.setContentType("application/x-msdownload");// iso-8859-1
            response.setHeader("Content-Disposition", "attachment; filename=\"" + URLEncoder.encode(fileName, "utf-8") + "\"");
//            System.out.println(fileName);
            OutputStream out = response.getOutputStream();

            FileInputStream in = new FileInputStream(new File(path));
            int i = 0;
            byte[] buffer = new byte[1024];

            while ((i = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, i);
            }
            out.close();
            out.flush();
            in.close();
            return null;
        }
        catch (Exception e)
        {
            String errorMsg = "下载过程中出错，请联系管理员";
            Results.createErrForDownOrExp(response, errorMsg);
            return error(e);
        }
    }

    /**
     * 上传文件，注意参数说明，参数内容不同，所做的功能也有所不同。
     * 
     * @param entityId
     *            -@QueryParam("entity_id") 上传完成后关联到实体的ID，可选参数
     * @param pictureId
     *            -@QueryParam("picture_id") 上传完成后关联到实体图片的ID，可选参数，注意： <li>a）大于0时表示修改pictureId对应的图片；</li>
     *            <li>b）等于-1且entityid大于0时表示在entityId对应的实体下增加一个图片。</li>
     * @param attachId
     *            -@QueryParam("attach_id") 上传完成后关联到附件的ID，可选参数，注意： <li>a）大于0时表示修改attachId对应的附件；</li>
     *            <li>b）等于-1且entityid大于0时表示在entityId对应的实体下增加一个附件。</li>
     * @param pathType
     *            -@QueryParam("path_type") 返回文件的地址类型，只对图片有效，<br>
     *            取值为：small-返回小图地址，middle-返回中图，big-返回原图地址，默认返回文件的json数据，多个文件时，只返回第一个文件
     * @return 上传文件实体
     */
    @POST
    public String upload(@QueryParam("entity_id")
    long entityId, @QueryParam("picture_id")
    long pictureId, @QueryParam("attach_id")
    long attachId, @QueryParam("path_type")
    String pathType)
    {
        try
        {
            // UploadFile upload = new UploadFile(request);
            // Xfile f = upload.upload(qr, owner);
            // String path = null;
            //
            // String[] paths = f.getPathArr();
            // if (!Format.isEmpty(pathType) && paths != null)
            // {
            // if ("small".equals(pathType))
            // {
            // path = paths[0];
            // }
            // else if ("middle".equals(pathType))
            // {
            // path = paths.length > 1 ? paths[1] : paths[0];
            // }
            // else if ("big".equals(pathType))
            // {
            // path = paths.length > 1 ? paths[2] : paths[0];
            // }
            // }

            String path = null;

            Xfile f = new Xfile(qr, owner);
            Upload upload = this.getUpload();
            List<Upload.Item> list = upload.go();
            if (list.size() > 0)
            {
                Upload.Item item = list.get(0);
                f.setName(item.getName()).setOrigin(item.getOrginalPath()).setSize(item.getSize()).setType(item.getType());
                if (item.getBigPath() != null)
                {
                    f.setSmall(item.getSmallPath()).setMiddle(item.getMiddlePath()).setBig(item.getBigPath());
                }
                f.insert();

                if (!Format.isEmpty(pathType))
                {
                    if ("small".equals(pathType))
                    {
                        path = item.getSmallPath();
                    }
                    else if ("middle".equals(pathType))
                    {
                        path = item.getMiddlePath();
                    }
                    else if ("big".equals(pathType))
                    {
                        path = item.getBigPath();
                    }
                }
            }

            // 在实体entityId下增加一个图片
            if (entityId > 0 && pictureId == -1)
            {
                EntityDao ed = new EntityDao(qr, owner, entityId);
                Picture pic = ed.addPicture(f.getFileId(), null);
                pic.addOtherValue(Xfile.PATH, f.getPath());
                pic.addOtherValue(Xfile.SMALL, f.getSmall());
                pic.addOtherValue(Xfile.MIDDLE, f.getMiddle());
                pic.addOtherValue(Xfile.BIG, f.getBig());
                if (Format.isEmpty(pathType))
                {
                    return ok(pic);
                }
            }
            // 在实体entityId下增加一个附件
            else if (entityId > 0 && attachId == -1)
            {
                EntityDao ed = new EntityDao(qr, owner, entityId);
                Attach att = ed.addAttach(f.getFileId(), null);
                att.addOtherValue(Xfile.PATH, f.getPath());
                att.addOtherValue(Xfile.SMALL, f.getSmall());
                att.addOtherValue(Xfile.MIDDLE, f.getMiddle());
                att.addOtherValue(Xfile.BIG, f.getBig());
                if (Format.isEmpty(pathType))
                {
                    addUrlLog(String.valueOf(att.getAttachId()), String.valueOf(att.getEntityId()));
                    return ok(att);
                }
            }
            else
            {

                if (entityId > 0)
                {
                    Entity e = new Entity(qr, owner);
                    e.setEntityId(entityId).setFileId(f.getFileId()).update(Entity.FILE_ID);
                }

                if (pictureId > 0)
                {
                    Picture pic = new Picture(qr, owner);
                    pic.setPictureId(pictureId).setName(f.getName()).setFileId(f.getFileId()).update(Picture.NAME);
                    pic.addOtherValue(Xfile.PATH, f.getPath());
                    pic.addOtherValue(Xfile.SMALL, f.getSmall());
                    pic.addOtherValue(Xfile.MIDDLE, f.getMiddle());
                    pic.addOtherValue(Xfile.BIG, f.getBig());
                    if (Format.isEmpty(pathType))
                    {
                        return ok(pic);
                    }
                }

                if (attachId > 0)
                {
                    Attach att = new Attach(qr, owner);
                    att.setAttachId(attachId).setName(f.getName()).setFileId(f.getFileId()).update(Attach.NAME);
                    att.addOtherValue(Xfile.PATH, f.getPath());
                    att.addOtherValue(Xfile.SMALL, f.getSmall());
                    att.addOtherValue(Xfile.MIDDLE, f.getMiddle());
                    att.addOtherValue(Xfile.BIG, f.getBig());
                    if (Format.isEmpty(pathType))
                    {
                        return ok(att);
                    }
                }
            }

            return path != null ? ok(path, HTML) : ok(f);
        }
        catch (Exception e)
        {
            return error(e);
        }
    }
}
